package com.ruoyi.demo.service.impl;


import com.ruoyi.demo.pojo.Result;
import com.ruoyi.demo.service.IFaceService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @projectName: utils
 * @package: com.example.demo.service.Impl
 * @className: IFaceServiceimpl
 * @author: tan
 * @description:
 */
@Service
public class IFaceServiceImpl implements IFaceService {

    // Python 服务地址
    @Value("${flask.host}")
    private String pythonServiceUrl;

    @Override
    public Result faceRecognize(MultipartFile image) {
        if (image != null && image.getOriginalFilename() != null && image.getOriginalFilename().length() > 0)
            try {
                MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                body.add("image", new ByteArrayResource(image.getBytes()) {
                    @Override
                    public String getFilename() {
                        return image.getOriginalFilename(); // 设置文件名
                    }
                });

                // 设置请求头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                // 发送请求到 Python 服务
                HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<Result> response = restTemplate.exchange(
                        pythonServiceUrl + "/recognize",
                        HttpMethod.POST,
                        requestEntity,
                        Result.class
                );
                return response.getBody();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        Result result = new Result();
        result.setMessage("!ERROR : Face Recognize，CANNOT Recognize Image");
        result.setStatus("3");
        return result;
    }

    @Override
    public Result faceRecognizeOnMeet(MultipartFile image, String meet_id) {
        if (image != null && image.getOriginalFilename() != null && image.getOriginalFilename().length() > 0)
            try {
                MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                body.add("meet_id", meet_id);
                body.add("image", new ByteArrayResource(image.getBytes()) {
                    @Override
                    public String getFilename() {
                        return image.getOriginalFilename(); // 设置文件名
                    }
                });

                // 设置请求头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                // 发送请求到 Python 服务
                HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<Result> response = restTemplate.exchange(
                        pythonServiceUrl + "/recognizeOnMeet",
                        HttpMethod.POST,
                        requestEntity,
                        Result.class
                );
                return response.getBody();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        Result result = new Result();
        result.setMessage("!ERROR : Face Recognize，CANNOT Recognize Image");
        result.setStatus("5");
        return result;
    }

    @Override
    public Result faceAdd(MultipartFile image, String user_id, String user_name, String nick_name) {
        if (image != null && image.getOriginalFilename() != null && image.getOriginalFilename().length() > 0) {
            try {
                // 构建请求体
                MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                body.add("user_id", user_id);
                body.add("user_name", user_name);
                body.add("nick_name", nick_name);
                body.add("image", new ByteArrayResource(image.getBytes()) {
                    @Override
                    public String getFilename() {
                        return image.getOriginalFilename(); // 设置文件名
                    }
                });

                // 设置请求头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                // 发送请求到 Python 服务
                HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<Result> response = restTemplate.exchange(
                        pythonServiceUrl + "/add_face",
                        HttpMethod.POST,
                        requestEntity,
                        Result.class
                );
                // 返回 Python 服务的响应
                return response.getBody();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        Result result = new Result();
        result.setMessage("!ERROR : Face Add，CANNOT Recognize Image");
        result.setStatus("5");
        return result;
    }
    @Override
    public String runPythonScript(String pythonScriptPath) {
        StringBuilder output = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            int exitCode = process.waitFor();
            output.append("Python脚本执行完毕，退出码: ").append(exitCode);
        } catch (Exception e) {
            e.printStackTrace();
            output.append("执行失败: ").append(e.getMessage());
        }
        return output.toString();
    }
}
